package map_set.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 复制带随机指针的链表
 * @Author Stark
 * @Date 2022/3/12 16:31
 **/
public class Num138_CopyRandomList {
    public Node copyRandomList(Node head) {
        if(head ==null){
            return null;
        }
        //用Map存储原结点和新结点的一一对应关系
        Map<Node,Node> map = new HashMap<>();
        for(Node node = head;node != null;node = node.next){
            map.put(node,new Node(node.val));
        }
        //根据原结点的关系通过键值对查到新结点的连接关系
        for(Node node = head;node != null;node = node.next){
            map.get(node).next = map.get(node.next);
            map.get(node).random = map.get(node.random);
        }
        return map.get(head);
    }
}
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
